<template>
  <div class="doctor-workstation">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="container">
        <h1 class="page-title">医生工作站</h1>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/portal' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>医生服务</el-breadcrumb-item>
          <el-breadcrumb-item>工作站</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>
    
    <!-- 主要内容 -->
    <div class="container main-content">
      <el-row :gutter="30">
        <!-- 左侧导航 -->
        <el-col :xs="24" :sm="24" :md="5" :lg="4" :xl="4">
          <div class="side-nav">
            <h3 class="side-nav-title">医生服务</h3>
            <el-menu
              class="side-menu"
              :default-active="activeMenu"
              @select="handleMenuSelect"
            >
              <el-menu-item index="dashboard">
                <el-icon><HomeFilled /></el-icon>
                <span>工作主页</span>
              </el-menu-item>
              <el-menu-item index="patients">
                <el-icon><User /></el-icon>
                <span>患者管理</span>
              </el-menu-item>
              <el-menu-item index="schedule">
                <el-icon><Timer /></el-icon>
                <span>排班管理</span>
              </el-menu-item>
              <el-menu-item index="records">
                <el-icon><Document /></el-icon>
                <span>就诊记录</span>
              </el-menu-item>
              <el-menu-item index="prescription">
                <el-icon><List /></el-icon>
                <span>处方管理</span>
              </el-menu-item>
            </el-menu>
            
            <div class="service-card">
              <h3 class="service-card-title">
                <el-icon><Service /></el-icon> 工作助手
              </h3>
              <p class="service-info">当前在线患者：{{ onlinePatients }}人</p>
              <p class="service-info">今日预约：{{ todayAppointments }}个</p>
            </div>
          </div>
        </el-col>
        
        <!-- 右侧内容 -->
        <el-col :xs="24" :sm="24" :md="19" :lg="20" :xl="20">
          <div class="workstation-content">
            <!-- 欢迎信息 -->
            <el-card class="welcome-card" v-if="activeComponent === 'dashboard'">
              <template #header>
                <div class="welcome-header">
                  <h2>欢迎，{{ doctorName }} {{ doctorTitle }}</h2>
                  <p>{{ currentTime }}</p>
                </div>
              </template>
              
              <div class="dashboard-stats">
                <el-row :gutter="20">
                  <el-col :xs="24" :sm="12" :md="6" :lg="6">
                    <div class="stat-card" style="background-color: #ecf5ff">
                      <div class="stat-icon" style="color: #409eff">
                        <el-icon><Calendar /></el-icon>
                      </div>
                      <div class="stat-info">
                        <div class="stat-value">{{ todayAppointments }}</div>
                        <div class="stat-label">今日预约</div>
                      </div>
                    </div>
                  </el-col>
                  
                  <el-col :xs="24" :sm="12" :md="6" :lg="6">
                    <div class="stat-card" style="background-color: #f0f9eb">
                      <div class="stat-icon" style="color: #67c23a">
                        <el-icon><User /></el-icon>
                      </div>
                      <div class="stat-info">
                        <div class="stat-value">{{ waitingPatients }}</div>
                        <div class="stat-label">待诊患者</div>
                      </div>
                    </div>
                  </el-col>
                  
                  <el-col :xs="24" :sm="12" :md="6" :lg="6">
                    <div class="stat-card" style="background-color: #fdf6ec">
                      <div class="stat-icon" style="color: #e6a23c">
                        <el-icon><Document /></el-icon>
                      </div>
                      <div class="stat-info">
                        <div class="stat-value">{{ todayCompletedAppointments }}</div>
                        <div class="stat-label">已完成就诊</div>
                      </div>
                    </div>
                  </el-col>
                  
                  <el-col :xs="24" :sm="12" :md="6" :lg="6">
                    <div class="stat-card" style="background-color: #fef0f0">
                      <div class="stat-icon" style="color: #f56c6c">
                        <el-icon><ChatDotRound /></el-icon>
                      </div>
                      <div class="stat-info">
                        <div class="stat-value">{{ unreadMessages }}</div>
                        <div class="stat-label">未读消息</div>
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </div>
              
              <!-- 快速操作区 -->
              <div class="quick-actions">
                <h3 class="section-title">快速操作</h3>
                <el-row :gutter="20">
                  <el-col :xs="12" :sm="8" :md="6" :lg="4">
                    <div class="action-card" @click="navigateTo('schedule')">
                      <el-icon><Timer /></el-icon>
                      <span>管理排班</span>
                    </div>
                  </el-col>
                  <el-col :xs="12" :sm="8" :md="6" :lg="4">
                    <div class="action-card" @click="navigateTo('patients')">
                      <el-icon><User /></el-icon>
                      <span>患者管理</span>
                    </div>
                  </el-col>
                  <el-col :xs="12" :sm="8" :md="6" :lg="4">
                    <div class="action-card" @click="navigateTo('records')">
                      <el-icon><Document /></el-icon>
                      <span>就诊记录</span>
                    </div>
                  </el-col>
                  <el-col :xs="12" :sm="8" :md="6" :lg="4">
                    <div class="action-card" @click="navigateTo('prescription')">
                      <el-icon><List /></el-icon>
                      <span>处方管理</span>
                    </div>
                  </el-col>
                </el-row>
              </div>
              
              <!-- 今日预约列表 -->
              <div class="today-appointments">
                <h3 class="section-title">今日预约</h3>
                <el-table :data="appointmentList" style="width: 100%" v-loading="loading">
                  <el-table-column prop="time" label="时间" width="100" />
                  <el-table-column prop="patientName" label="患者姓名" width="120" />
                  <el-table-column prop="gender" label="性别" width="80" />
                  <el-table-column prop="age" label="年龄" width="80" />
                  <el-table-column prop="reason" label="就诊原因" show-overflow-tooltip />
                  <el-table-column prop="status" label="状态" width="100">
                    <template #default="scope">
                      <el-tag :type="getStatusType(scope.row.status)">
                        {{ getStatusText(scope.row.status) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="200" fixed="right">
                    <template #default="scope">
                      <el-button 
                        size="small" 
                        type="primary" 
                        @click="handleView(scope.row)"
                        :disabled="scope.row.status === 'cancelled'"
                      >
                        查看
                      </el-button>
                      <el-button 
                        size="small" 
                        type="success" 
                        @click="handleStart(scope.row)"
                        v-if="scope.row.status === 'confirmed'"
                      >
                        开始就诊
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-card>
            
            <!-- 动态加载的组件 -->
            <component 
              v-if="activeComponent !== 'dashboard'"
              :is="components[activeComponent]" 
              @refresh-data="loadData"
            ></component>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, markRaw, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { doctorAPI, appointmentAPI, patientAPI } from '@/utils/api'
import { format } from 'date-fns'
import { 
  Calendar, 
  User, 
  Document, 
  Timer, 
  List, 
  ChatDotRound, 
  Service, 
  HomeFilled,
  FirstAidKit
} from '@element-plus/icons-vue'

// 导入医生工作站子组件
import DoctorPatients from './DoctorPatients.vue'
import DoctorSchedule from './DoctorSchedule.vue'
import DoctorRecords from './DoctorRecords.vue'
import DoctorPrescription from './DoctorPrescription.vue'

// 路由实例
const router = useRouter()
const userStore = useUserStore()

// 动态组件注册
const components = {
  DoctorPatients: markRaw(DoctorPatients),
  DoctorSchedule: markRaw(DoctorSchedule),
  DoctorRecords: markRaw(DoctorRecords),
  DoctorPrescription: markRaw(DoctorPrescription)
}

// 数据加载状态
const loading = ref(false)

// 当前活动菜单
const activeMenu = ref('dashboard')

// 当前活动组件
const activeComponent = ref('dashboard')

// 医生信息
const doctorName = ref('')
const doctorTitle = ref('')
const doctorId = ref('')

// 统计数据
const onlinePatients = ref(0)
const todayAppointments = ref(0)
const waitingPatients = ref(0)
const todayCompletedAppointments = ref(0)
const unreadMessages = ref(0)

// 当前时间
const currentTime = ref('')

// 预约列表
const appointmentList = ref([])

// 更新当前时间
const updateCurrentTime = () => {
  const now = new Date()
  currentTime.value = format(now, 'yyyy年MM月dd日 HH:mm:ss')
}

// 获取医生信息
const getDoctorInfo = async () => {
  try {
    if (!userStore.isLoggedIn || userStore.userRole !== 'doctor') {
      ElMessage.warning('请以医生身份登录后使用')
      router.push('/portal/login')
      return
    }

    // 获取用户ID
    const userId = userStore.userInfo?.id || userStore.userInfo?._id

    if (!userId) {
      ElMessage.error('获取用户信息失败')
      return
    }

    // 获取医生详细信息
    const res = await doctorAPI.getDoctorByUserId(userId)

    if (res.success && res.data) {
      const doctorInfo = res.data
      doctorName.value = doctorInfo.name || userStore.name || '医生'
      doctorTitle.value = doctorInfo.title || '医师'
      doctorId.value = doctorInfo.id || doctorInfo._id || userId

      // 加载医生的预约数据
      loadAppointmentData()
    } else {
      // 如果没有找到医生信息，使用用户信息
      doctorName.value = userStore.name || '医生'
      doctorTitle.value = '医师'
      doctorId.value = userId

      // 加载默认数据
      loadMockData()
    }
  } catch (error) {
    console.error('获取医生信息失败:', error)
    // 使用默认值
    doctorName.value = userStore.name || '医生'
    doctorTitle.value = '医师'
    doctorId.value = userStore.userInfo?.id || userStore.userInfo?._id || ''
    
    // 加载默认数据
    loadMockData()
  }
}

// 加载预约数据
const loadAppointmentData = async () => {
  try {
    loading.value = true
    
    // 获取今日日期
    const today = new Date()
    const dateStr = format(today, 'yyyy-MM-dd')
    
    // 查询医生今日预约
    const res = await appointmentAPI.getAppointments({
      doctorId: doctorId.value,
      date: dateStr,
      status: 'all'
    })
    
    if (res.success && res.data) {
      // 处理预约数据
      const appointments = res.data.appointments || res.data.items || []
      
      // 更新统计数据
      todayAppointments.value = appointments.length
      waitingPatients.value = appointments.filter(a => a.status === 'confirmed').length
      todayCompletedAppointments.value = appointments.filter(a => a.status === 'completed').length
      
      // 格式化预约列表
      appointmentList.value = appointments.map(appointment => ({
        id: appointment.id || appointment._id,
        time: appointment.timeSlot || '09:00-10:00',
        patientName: appointment.patientName || '未知患者',
        gender: appointment.patientGender === 'male' ? '男' : '女',
        age: appointment.patientAge || '未知',
        reason: appointment.visitReason || appointment.remarks || '常规就诊',
        status: appointment.status || 'pending'
      }))
    } else {
      // 加载默认数据
      loadMockData()
    }
  } catch (error) {
    console.error('加载预约数据失败:', error)
    // 加载默认数据
    loadMockData()
  } finally {
    loading.value = false
  }
}

// 加载模拟数据（当API请求失败时使用）
const loadMockData = () => {
  // 模拟统计数据
  onlinePatients.value = Math.floor(Math.random() * 20) + 5
  todayAppointments.value = Math.floor(Math.random() * 15) + 5
  waitingPatients.value = Math.floor(Math.random() * 8) + 2
  todayCompletedAppointments.value = Math.floor(Math.random() * 5)
  unreadMessages.value = Math.floor(Math.random() * 10)
  
  // 模拟预约列表
  const mockNames = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十']
  const mockReasons = ['感冒发热', '头痛', '腹痛', '咳嗽', '皮疹', '常规复诊', '血压检查', '糖尿病随访']
  const mockStatuses = ['pending', 'confirmed', 'completed', 'cancelled']
  
  const mockAppointments = []
  
  for (let i = 0; i < todayAppointments.value; i++) {
    const hour = 8 + Math.floor(i / 2)
    const minute = (i % 2) * 30
    const hourStr = hour < 10 ? `0${hour}` : `${hour}`
    const minuteStr = minute === 0 ? '00' : '30'
    const time = `${hourStr}:${minuteStr}-${hourStr}:${minuteStr === '00' ? '30' : '00'}`
    
    mockAppointments.push({
      id: `mock-appt-${i}`,
      time: time,
      patientName: mockNames[Math.floor(Math.random() * mockNames.length)],
      gender: Math.random() > 0.5 ? '男' : '女',
      age: Math.floor(Math.random() * 60) + 10,
      reason: mockReasons[Math.floor(Math.random() * mockReasons.length)],
      status: mockStatuses[Math.floor(Math.random() * mockStatuses.length)]
    })
  }
  
  appointmentList.value = mockAppointments
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    'pending': 'info',
    'confirmed': 'primary',
    'completed': 'success',
    'cancelled': 'danger',
    'no_show': 'warning'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    'pending': '待确认',
    'confirmed': '已确认',
    'completed': '已完成',
    'cancelled': '已取消',
    'no_show': '未到诊'
  }
  return texts[status] || '未知'
}

// 处理菜单选择
const handleMenuSelect = (key) => {
  activeMenu.value = key
  
  // 根据菜单项加载不同组件
  switch (key) {
    case 'dashboard':
      activeComponent.value = 'dashboard'
      loadData()
      break
    case 'patients':
      activeComponent.value = 'DoctorPatients'
      break
    case 'schedule':
      activeComponent.value = 'DoctorSchedule'
      break
    case 'records':
      activeComponent.value = 'DoctorRecords'
      break
    case 'prescription':
      activeComponent.value = 'DoctorPrescription'
      break
    default:
      activeComponent.value = 'dashboard'
  }
}

// 导航到指定页面
const navigateTo = (key) => {
  handleMenuSelect(key)
}

// 处理查看预约
const handleView = (appointment) => {
  // 由于预约详情页面已被移除，直接跳转到就诊页面
  if (appointment.status === 'confirmed') {
    handleStart(appointment)
  } else {
    ElMessage.info('请在患者管理页面查看详细信息')
  }
}

// 处理开始就诊
const handleStart = (appointment) => {
  // 开始就诊逻辑，可以导航到就诊页面
  router.push(`/portal/doctor/consultation/${appointment.id}`)
}

// 加载数据
const loadData = () => {
  // 更新时间
  updateCurrentTime()
  
  // 加载预约数据
  if (doctorId.value) {
    loadAppointmentData()
  } else {
    loadMockData()
  }
}

// 组件挂载时
onMounted(() => {
  // 获取医生信息
  getDoctorInfo()
  
  // 更新当前时间
  updateCurrentTime()
  
  // 设置定时器，每秒更新一次时间
  const timer = setInterval(updateCurrentTime, 1000)
  
  // 组件卸载时清除定时器
  onUnmounted(() => {
    clearInterval(timer)
  })
})
</script>

<style scoped>
.doctor-workstation {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 40px;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  background-color: white;
  padding: 20px 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 30px;
}

.page-title {
  font-size: 24px;
  color: #333;
  margin: 0 0 10px;
}

.main-content {
  margin-bottom: 40px;
}

.side-nav {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.side-nav-title {
  font-size: 18px;
  margin: 0;
  padding: 20px;
  background: #1989fa;
  color: white;
}

.side-menu {
  border-right: none;
}

.service-card {
  padding: 20px;
  background: #f0f9ff;
  margin-top: 20px;
  border-radius: 0 0 8px 8px;
}

.service-card-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  margin: 0 0 10px;
  color: #1989fa;
}

.service-card-title .el-icon {
  margin-right: 5px;
}

.service-info {
  font-size: 14px;
  color: #666;
  margin: 10px 0;
}

.workstation-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 0;
  overflow: visible;
  width: 100%;
  min-width: 0;
}

.welcome-card {
  margin-bottom: 0;
  border: none;
  box-shadow: none;
}

.welcome-card :deep(.el-card__header) {
  padding: 20px;
  background: #f8f9fa;
}

/* 确保动态组件有足够的空间 */
.workstation-content > :deep(.doctor-schedule) {
  width: 100%;
  padding: 0;
}

.workstation-content > :deep(.doctor-patients) {
  width: 100%;
  padding: 0;
  min-width: 1200px;
  overflow-x: auto;
}

.workstation-content :deep(.el-table) {
  width: 100% !important;
}

.workstation-content :deep(.el-card) {
  margin-bottom: 0;
  border: none;
  box-shadow: none;
}

/* 确保表格容器有足够的宽度 */
.workstation-content :deep(.el-card__body) {
  overflow-x: auto;
  min-width: 0;
}

.welcome-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.welcome-header h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.welcome-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.dashboard-stats {
  margin: 20px 0 30px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.stat-icon {
  font-size: 24px;
  margin-right: 15px;
  padding: 15px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.section-title {
  font-size: 18px;
  margin: 0 0 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.quick-actions {
  margin-bottom: 30px;
}

.action-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 20px;
}

.action-card:hover {
  background: #ecf5ff;
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.action-card .el-icon {
  font-size: 24px;
  margin-bottom: 10px;
  color: #1989fa;
}

.today-appointments {
  margin-bottom: 20px;
}

.text-secondary {
  color: #909399;
  font-size: 12px;
}

@media (min-width: 1400px) {
  .container {
    max-width: 1600px;
  }
  
  .workstation-content {
    overflow-x: auto;
  }
}

@media (max-width: 1300px) {
  .container {
    max-width: 100%;
    padding: 0 10px;
  }
  
  .workstation-content {
    overflow-x: auto;
  }
}

@media (max-width: 768px) {
  .workstation-content {
    padding: 20px;
  }
  
  .side-nav {
    margin-bottom: 20px;
  }
  
  .stat-card {
    margin-bottom: 15px;
  }
}
</style> 